package org.newlucene.core.search;

import java.io.IOException;

import org.newlucene.core.search.HitCollector;
import org.newlucene.core.search.HitQueue;
import org.newlucene.core.search.ScoreDoc;

public class SimpleHitCollector implements HitCollector
{
	private float minScore = 0.0f;
	private HitQueue hq;
	private int capacity;
	private int totalHits = 0;

	public SimpleHitCollector(int capacity) throws IOException
	{
		hq = new HitQueue(capacity);
		this.capacity = capacity;
	}
	
	public void collect(int doc, float score) 
	{
		// ignore zeroed buckets and skip docs not in bits
		totalHits++;
		if (score >= minScore) 
		{
			hq.put(new ScoreDoc(doc, score)); // update hit queue
			// if hit queue overfull
			if (hq.size() > capacity) 
			{ 
				// remove lowest in hit queue
				hq.pop();
				
				// reset minScore
				minScore = ((ScoreDoc) hq.top()).getScore();
			}
		}
	}
	
	public int getTotalHits()
	{
		return totalHits;
	}
	
	public ScoreDoc[] getScoreDocs()
	{
		ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()];
		int i = scoreDocs.length - 1;
		while (hq.top() != null)
		{
			scoreDocs[i] = (ScoreDoc) hq.pop();
			i--;
		}
		return scoreDocs; 
	}
	
	public int getNumScoreDocs()
	{
		return hq.size();
	}
	
	public int getCapacity()
	{
		return capacity;
	}
}